<?php
namespace cms\modules\common\models;

use common\models\Status;
use Yii;
use yii\base\Exception;
use yii\web\IdentityInterface;
/**
 * UserBackend model，这是user组件在后台认证的类
 * 集成了IdentityInterface这个认证接口（抽象类），注意：要实现抽象类中的所有方法
 *
 */
class Admin extends Login
{
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return '{{%admin_info}}';
    }


    /**
     * Finds user by username
     *
     * @param string $username
     * @return static|null
     */
    public static function findByUsername($username)
    {
        return static::findOne(['login_name' => $username, 'status' => Status::COMMON_STATUS_SHOW]);
    }

    /**
     * Finds user by password reset token
     *c
     * @param string $token password reset token
     * @return static|null
     */
    public static function findByPasswordResetToken($token)
    {
        if (!static::isPasswordResetTokenValid($token)) {
            return null;
        }

        return static::findOne([
            'password_reset_token' => $token,
            'status' => Status::COMMON_STATUS_SHOW,
        ]);
    }

    /**
     * 重置密码时  临时TOKEN验证
     *
     * @param string $token password reset token
     * @return bool
     */
    public static function isPasswordResetTokenValid($token)
    {
        if (empty($token)) {
            return false;
        }

        $timestamp = (int) substr($token, strrpos($token, '_') + 1);
        $expire = Yii::$app->params['user.passwordResetTokenExpire'];
        return $timestamp + $expire >= time();
    }

    /**
     * Validates password
     *
     * @param string $password password to validate
     * @return bool if password provided is valid for current user
     */
    public function validatePassword($password)
    {
        return Yii::$app->security->validatePassword($password, $this->password_hash);
    }

    /**
     * Generates password hash from password and sets it to the model
     *
     * @param string $password
     */
    public function setPassword($password)
    {
        $this->password_hash = Yii::$app->security->generatePasswordHash($password);
    }

    /**
     * 记住我时，cookie存储的token
     * Generates "remember me" authentication key
     */
    public function generateAuthKey()
    {
        $this->access_token = Yii::$app->security->generateRandomString() . '_' . time();
        $this->refresh_token = Yii::$app->security->generateRandomString() . '_' . time();
    }

    /**
     * 重置密码时，临时token
     * Generates new password reset token
     */
    public function generatePasswordResetToken()
    {
        $this->password_reset_token = Yii::$app->security->generateRandomString() . '_' . time();
    }

    /**
     * 临时token失效
     * Removes password reset token
     */
    public function removePasswordResetToken()
    {
        $this->password_reset_token = null;
    }


    /**
     * 验证用户登录token
     * @param string $refreshToken
     * @return bool
     */
    public static function refreshTokenIsValid($refreshToken = '') {
        if (empty($refreshToken)) {
            return false;
        }

        $timestamp = (int) substr($refreshToken, strripos($refreshToken, '_') + 1);
        $expire = Yii::$app->params['user.RefreshToken'];
        return $timestamp + $expire >= time();
    }

    /**
     * 验证用户登录token
     * @param $token
     *
     * @return bool
     */
    public static function authKeyIsValid($token) {
        if (empty($token)) {
            return false;
        }

        $timestamp = (int) substr($token, strripos($token, '_') + 1);
        $expire = Yii::$app->params['user.AccessToken'];
        return $timestamp + $expire >= time();
    }

    /**
     * 判断登录是否有效
     * @param $token
     * @return bool|mixed
     */
    public function getAdminId($token) {
        // 如果token无效的话，
        if(!static::authKeyIsValid($token)) {
            return false;
        }
        $admin = static::findIdentityByAccessToken($token);
        if($admin) {
            return $admin->id;
        }
        return false;
    }

    /**
     * 检查用于信息
     * @return array|null|\yii\db\ActiveRecord
     * @throws Exception
     */
    public function checkLogin() {
        $accessToken = Yii::$app->request->headers->get('access-token');
        $adminId = $this->getAdminId($accessToken);
        if(!$adminId) {
            throw new Exception('登录已过期，请重新登录');
        }
        $adminInfo = static::getOneByWhere(['id' => $adminId]);
        if(empty($adminInfo)) {
            throw new Exception('未知用户');
        }
        return $adminInfo;
    }

    /**
     * 验证登录
     * @param $token
     * @param null $type
     * @return null|IdentityInterface|static
     */
    public function loginByAccessToken($token, $type = null)
    {
        /* @var $class IdentityInterface */
        $identity = static::findIdentityByAccessToken($token, $type);
        if ($identity && Yii::$app->user->login($identity)) {
            return $identity;
        }

        return null;
    }
}
